package cn.legend.travel.admin.destination.service.impl;

import cn.legend.travel.admin.destination.dao.persist.repository.ISceneryDetailRepository;
import cn.legend.travel.admin.destination.dao.persist.repository.ISceneryRepository;
import cn.legend.travel.admin.destination.pojo.entity.Scenery;
import cn.legend.travel.admin.destination.pojo.param.SceneryAddNewParam;
import cn.legend.travel.admin.destination.pojo.param.SceneryUpdateParam;
import cn.legend.travel.admin.destination.pojo.vo.SceneryAdminVO;
import cn.legend.travel.admin.destination.service.ISceneryService;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.common.pojo.vo.PageData;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class SceneryServiceImpl implements ISceneryService {
    @Value("${travel.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    private final ISceneryRepository sceneryRepository;
    private final ISceneryDetailRepository sceneryDetailRepository;

    @Override
    public PageData<SceneryAdminVO> list(int pageNum) {
        return sceneryRepository.list(pageNum, defaultQueryPageSize);
    }

    @Override
    @Transactional
    public void update(SceneryUpdateParam param) {
        int row = sceneryRepository.update(param);
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERROR_UPDATE, "服务器忙,请稍后再试.");
        }
        row = sceneryDetailRepository.update(param.getId(), param.getContent());
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERROR_UPDATE, "服务器忙,请稍后再试.");
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        int row = sceneryRepository.delete(id);
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERROR_DELETE, "服务器忙,请稍后再试.");
        }
        row = sceneryDetailRepository.deleteByScenery(id);
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERROR_DELETE, "服务器忙,请稍后再试.");
        }
    }

    @Override
    @Transactional
    public void addNew(SceneryAddNewParam param) {
        Long id = sceneryRepository.addNew(param);
        int row = sceneryDetailRepository.addNew(id, param.getContent());
        if (row != 1) {
            throw new ServiceException(ServiceCode.ERROR_INSERT, "服务器忙,请稍后再试.");
        }
    }
}
